<?php

namespace Lowpress\PressExtensionsBundle\Feeds;

use Lowpress\PressBundle\Feeds\IFeedGatherer;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Lowpress\PressExtensionsBundle\Entity\Dribbble;

class DribbbleFeedGatherer implements IFeedGatherer
{

  public function __construct($username)
  {
    $this->username = $username;
  }

  public function gather(ContainerInterface $container)
  {
    $doctrine = $container->get("doctrine");
    $dribbble_repository = $doctrine->getRepository('LowpressPressExtensionsBundle:Dribbble');
    $em = $doctrine->getEntityManager();
    $last_dribble = $dribbble_repository->findOneBy(array(), array('created', 'DESC'));

    $feed = json_decode(file_get_contents("http://api.dribbble.com/players/".$this->username."/shots"));

    foreach ($feed->shots as $shot)
    {
      $date = new \DateTime($shot->created_at);
      $date->setTimeZone(new \DateTimeZone(date_default_timezone_get()));

      if (!$last_dribble || ($last_dribble && $date > $last_dribble->getCreated())){
        $dribbble = new Dribbble();
        $dribbble->setTitle($shot->title);
        $dribbble->setImageUrl($shot->image_url);
        $dribbble->setCreated($date);
        $dribbble->setImageTeaserUrl($shot->image_teaser_url);
        $em->persist($dribbble);
      }
    }
    $em->flush();
  }
}

?>